package com.ruike.alisurface.ui.settings;

import android.os.Bundle;
import android.os.SystemClock;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Switch;
import android.widget.TextView;

import com.lgh.uvccamera.utils.ThreadUtils;
import com.ruike.alisurface.Constant;
import com.ruike.alisurface.R;
import com.ruike.alisurface.base.BaseAty;
import com.ruike.alisurface.bean.AisleSlotTime;
import com.ruike.alisurface.https.ShopApiHttp;
import com.ruike.alisurface.printer.OrderTicketBean;
import com.ruike.alisurface.printer.PrinterOperateUtils;
import com.ruike.alisurface.serialport.MsgEventBus;
import com.ruike.alisurface.serialport.QrCodeUtils;
import com.ruike.alisurface.serialport.Ttys3Utils;
import com.ruike.alisurface.serialport.serial.SerialPortInstructUtils;
import com.ruike.alisurface.utils.CountTimeUtils;
import com.ruike.alisurface.utils.ShareKey;
import com.voodoo.lib_http.ApiListener;
import com.voodoo.lib_logcat.L;
import com.voodoo.lib_utils.SharedUtils;

import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class BaseSetting_Aty extends BaseAty {

    @BindView(R.id.base_buyQuantity_et)
    EditText baseBuyQuantityEt;
    @BindView(R.id.base_buyQuantitySave_btn)
    Button baseBuyQuantitySaveBtn;
    @BindView(R.id.base_showAdv_swch)
    Switch baseShowAdvSwch;
    @BindView(R.id.base_showprinter_swch)
    Switch baseShowprinterSwch;
    boolean isprinter;
    @BindView(R.id.bt_printreceipt)
    Button btPrintreceipt;
    @BindView(R.id.bt_qrcode)
    Button btQrcode;
    @BindView(R.id.bt_qrcode_text)
    TextView btQrcodeText;

    @BindView(R.id.aisle_ed)
    EditText aisleEd;
    @BindView(R.id.aisle_time_ed)
    EditText aisleTimeEd;
    @BindView(R.id.aisle_time_ed_start)
    EditText aisleTimeEdStart;
    @BindView(R.id.aisle_time_ed_end)
    EditText aisleTimeEdEnd;
    @BindView(R.id.text_tv)
    TextView textTv;
    @BindView(R.id.bt_start_humidifier)
    Button btStartHumidifier;
    @BindView(R.id.bt_Open_the_refrigeration)
    Button btOpenTheRefrigeration;
    @BindView(R.id.bt_Open_the_heating)
    Button btOpenTheHeating;
    @BindView(R.id.bt_Stop_temperature_control)
    Button btStopTemperatureControl;
    List<Button> btlist = new ArrayList<>();

    @Override
    protected int getLayoutResId() {
        return R.layout.app_base_setting;
    }

    @Override
    protected void initViews() {
        initTitleBar(false);
        btlist.add(btStartHumidifier);
        btlist.add(btOpenTheRefrigeration);
        btlist.add(btOpenTheHeating);
        btlist.add(btStopTemperatureControl);


    }

    @Override
    protected void initData() {
        int buynumber = SharedUtils.getInstance().getInt(ShareKey.PURCHASE_COUNT, 3); // 购买数量
        baseBuyQuantityEt.setText(buynumber + "");
        int advType = SharedUtils.getInstance().getInt(Constant.AdvType.ADV_TYPE_KEY);
        if (advType == 2) {
            baseShowAdvSwch.setChecked(false);
        } else {
            baseShowAdvSwch.setChecked(true);
        }
        isprinter = SharedUtils.getInstance().getBoolean(ShareKey.IS_PRINTER, true);
        baseShowprinterSwch.setChecked(isprinter);
        btPrintreceipt.setVisibility(isprinter ? View.VISIBLE : View.GONE);
    }

    List<AisleSlotTime.slotTimeBean> slotTimesList = new ArrayList<>();
    int mSlotIndex = 1;
    StringBuilder builder = new StringBuilder();

    @OnClick({R.id.goback_imgv, R.id.base_buyQuantitySave_btn, R.id.base_showAdv_swch, R.id.base_showprinter_swch,
            R.id.bt_printreceipt, R.id.bt_qrcode, R.id.bt_write_time, R.id.bt_setting_aisle, R.id.bt_setting_save,
            R.id.bt_write_moretime, R.id.bt_start_humidifier, R.id.bt_Open_the_refrigeration, R.id.bt_Open_the_heating, R.id.bt_Stop_temperature_control})
    @Override
    public void onClick(View view) {
        super.onClick(view);
        switch (view.getId()) {
            case R.id.goback_imgv:
                finish();
                break;
            case R.id.base_buyQuantitySave_btn:
                String buyQuantityStr = baseBuyQuantityEt.getText().toString().trim();
                if (!buyQuantityStr.isEmpty()) {
                    int buyQuantity = Integer.parseInt(buyQuantityStr);
                    if (buyQuantity > 0) {
                        if(buyQuantity>12){
                            showErrorToast("购买数量不能超过12");
                            return;
                        }
                        showRightToast("设置成功");
                        setCount(buyQuantityStr);
                    } else {
                        showErrorToast("购买数量不能为零");
                    }
                } else {
                    showErrorToast("购买数量不能为空");
                }
                break;

            case R.id.base_showAdv_swch:
                SharedUtils.getInstance().putInt(Constant.AdvType.ADV_TYPE_KEY, baseShowAdvSwch.isChecked()
                        ? Constant.AdvType.IMAVE : Constant.AdvType.NONE); // 选中的话为轮播图广告，关闭的话状态为2

                showRightToast("设置成功");
                break;
            case R.id.base_showprinter_swch:
                isprinter = !isprinter;
                SharedUtils.getInstance().putBoolean(ShareKey.IS_PRINTER, isprinter);
                showRightToast("设置成功");
                break;
            case R.id.bt_printreceipt:
                showRightToast("开始打印小票");
                setPrinter();
                break;
            case R.id.bt_qrcode:

                showRightToast("点击了反扫");
                QrCodeUtils.sendCommandCode();

                break;
            case R.id.bt_write_time:
                if (TextUtils.isEmpty(aisleEd.getText())) {
                    showErrorToast("层不能为空");
                    return;
                }

                if (TextUtils.isEmpty(aisleTimeEd.getText())) {
                    showErrorToast("转动时间不能为空");
                    return;
                }

                mSlotIndex = mSlotIndex * Integer.parseInt(aisleEd.getText().toString());
                AisleSlotTime.slotTimeBean stdata = new AisleSlotTime.slotTimeBean();
                stdata.setSlotIndex(mSlotIndex++);
                stdata.setSlotTime(Integer.parseInt(aisleTimeEd.getText().toString()) * 10);
                slotTimesList.add(stdata);
                builder = new StringBuilder();
                builder.append("每次单个货道转动时间数据==第").append(Integer.parseInt(aisleEd.getText().toString()) + "=层=")
                        .append(slotTimesList.toString());
                textTv.setText(builder.toString());

                break;
            case R.id.bt_write_moretime:
                if (TextUtils.isEmpty(aisleEd.getText())) {
                    showErrorToast("层不能为空");
                    return;
                }

                if (TextUtils.isEmpty(aisleTimeEd.getText())) {
                    showErrorToast("转动时间不能为空");
                    return;
                }

                if (TextUtils.isEmpty(aisleTimeEdStart.getText())) {
                    showErrorToast("起始货道不能为空");
                    return;
                }

                if (TextUtils.isEmpty(aisleTimeEdEnd.getText())) {
                    showErrorToast("结束货道不能为空");
                    return;
                }

                int start = Integer.parseInt(aisleTimeEdStart.getText().toString());
                int end = Integer.parseInt(aisleTimeEdEnd.getText().toString());
                mSlotIndex = 1;
                slotTimesList.clear();
                int aisle = Integer.parseInt(aisleEd.getText().toString());
                if (aisle > 1) {
                    mSlotIndex = mSlotIndex * 10 * aisle + 1;
                } else {
                    mSlotIndex = mSlotIndex * aisle;
                }
                for (int i = start; i < end; i++) {
                    AisleSlotTime.slotTimeBean addstdata = new AisleSlotTime.slotTimeBean();
                    addstdata.setSlotIndex(mSlotIndex++);
                    addstdata.setSlotTime(Integer.parseInt(aisleTimeEd.getText().toString()) * 10);
                    slotTimesList.add(addstdata);
                }
                builder = new StringBuilder();
                builder.append("每次货道转动时间数据==第").append(Integer.parseInt(aisleEd.getText().toString()) + "=层=")
                        .append(slotTimesList.toString());
                textTv.setText(builder.toString());
                break;
            case R.id.bt_setting_aisle:

                List<Integer> mlist = new ArrayList<>();
                for (AisleSlotTime.slotTimeBean data : slotTimesList) {
                    mlist.add(data.getSlotTime());
                }
                showRightToast("设置的每次货道转动时间指令");
                L.i("设置每次货道转动时间指令-" + SerialPortInstructUtils.set_Aisle_rotation_time(10,
                        Integer.parseInt(aisleEd.getText().toString()), mlist));
                Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.set_Aisle_rotation_time(10,
                        Integer.parseInt(aisleEd.getText().toString()), mlist));
                builder.append("设置每次货道转动时间数据==").append(slotTimesList.toString())
                        .append("==指令==" + SerialPortInstructUtils.set_Aisle_rotation_time(10,
                                Integer.parseInt(aisleEd.getText().toString()), mlist)).append("\n");
                textTv.setText(builder.toString());
                mSlotIndex = 1;
                slotTimesList.clear();
                break;
            case R.id.bt_setting_save:
                slotTimesList.clear();
                mSlotIndex = 1;
                showRightToast("设置保存所有的货道转动时间指令");
                builder.append("设置保存所有的货道转动时间指令==").append(SerialPortInstructUtils.set_save_all_rotation_time(10)).append("\n");
                L.i("设置保存所有的货道转动时间指令-" + SerialPortInstructUtils.set_save_all_rotation_time(10));
                Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.set_save_all_rotation_time(10));
                textTv.setText(builder.toString());
                break;
            case R.id.bt_start_humidifier:
                btSelected(view.getId());
                ThreadUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.temperatureControl(2, 0));
                        SystemClock.sleep(500);
                        Ttys3Utils.getInstance().isHumidifier(true);
                    }
                });

                break;
            case R.id.bt_Open_the_refrigeration:
                btSelected(view.getId());
                ThreadUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        Ttys3Utils.getInstance().isHumidifier(false);
                        SystemClock.sleep(500);
                        Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.temperatureControl(0, 2, 5));
                    }
                });
                break;
            case R.id.bt_Open_the_heating:
                btSelected(view.getId());
                ThreadUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        Ttys3Utils.getInstance().isHumidifier(false);
                        SystemClock.sleep(500);
                        Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.temperatureControl(1, 1, 45));

                    }
                });
                break;
            case R.id.bt_Stop_temperature_control:
                btSelected(view.getId());
                ThreadUtils.post(new Runnable() {
                    @Override
                    public void run() {
                        Ttys3Utils.getInstance().isHumidifier(false);
                        SystemClock.sleep(500);
                        Ttys3Utils.getInstance().sendHexData(SerialPortInstructUtils.temperatureControl(2, 0));
                    }
                });
                break;
        }
    }

    public void btSelected(int vid) {
        for (Button bts : btlist) {
            if (bts.getId() == vid) {
                bts.setSelected(true);
            } else {
                bts.setSelected(false);
            }
        }
    }

    public void setPrinter() {
        PrinterOperateUtils.getInstance().connectUsbPrinter(this);
        new CountTimeUtils(2) {
            @Override
            public void onTick(long mMillisUntilFinished) {

            }

            @Override
            public void onFinish() {
                if (!PrinterOperateUtils.getInstance().isConnected()) {
                    L.i("没有连接成功");
                    showErrorLongToast("打印小票没有连接成功", 5000);
                    return;
                }
                OrderTicketBean.DataBean orderTicketBean = new OrderTicketBean.DataBean();
                orderTicketBean.setDeviceName("天津睿科");
                orderTicketBean.setPhoneNumber("13800000831");
                orderTicketBean.setPayTime("2021年07月26日");
                orderTicketBean.setOrderId("2021072310462720572625");

                List<OrderTicketBean.DataBean.ProductBeansBean> productBeans = new ArrayList<>();
                OrderTicketBean.DataBean.ProductBeansBean productBean1 = new OrderTicketBean.DataBean.ProductBeansBean();
                productBean1.setProductName("感冒灵（999）");
                productBean1.setSpecification("15/盒");
                productBean1.setUnitPrice(15);
                productBean1.setNumber(1);
                productBean1.setSubtotal(15.00);
                productBeans.add(productBean1);
                OrderTicketBean.DataBean.ProductBeansBean productBean2 = new OrderTicketBean.DataBean.ProductBeansBean();
                productBean2.setProductName("感冒清热颗粒");
                productBean2.setSpecification("5.70/盒");
                productBean2.setUnitPrice(5.70);
                productBean2.setNumber(1);
                productBean2.setSubtotal(7.50);
                productBeans.add(productBean2);

                orderTicketBean.setProductBeans(productBeans);
                orderTicketBean.setTotalPay(22.50);
                orderTicketBean.setCash(22.50);
                orderTicketBean.setMedicalInsurance(0);
                orderTicketBean.setActualTotalPay(20.50);
                orderTicketBean.setIsPrintExhort(true);
                List<OrderTicketBean.DataBean.ExhortBeansBean> exhortBeans = new ArrayList<>();
                OrderTicketBean.DataBean.ExhortBeansBean exhortBean1 = new OrderTicketBean.DataBean.ExhortBeansBean();
                exhortBean1.setProductName("感冒灵（999）");
                exhortBean1.setDescribe("开水冲服。一次10克(1袋)，一日3次。严重肝肾功能不全者禁用。");
                exhortBeans.add(exhortBean1);
                OrderTicketBean.DataBean.ExhortBeansBean exhortBean2 = new OrderTicketBean.DataBean.ExhortBeansBean();
                exhortBean2.setProductName("感冒清热颗粒");
                exhortBean2.setDescribe("开水冲服。一次1袋，一日2次，对本品过敏者禁用。严重肝肾功能不全者禁用。");
                exhortBeans.add(exhortBean2);
                orderTicketBean.setExhortBeans(exhortBeans);
                orderTicketBean.setIsPrintQrCode(true);
                orderTicketBean.setQrcode("{\"order_id\":\"2021080511310400028834\"}");
                orderTicketBean.setQrcodeDescribe("扫描二维码申请开票");
                // 打印属于耗时操作，在异步线程完成
                new Thread() {
                    @Override
                    public void run() {
                        PrinterOperateUtils.getInstance().printOrder(getResources(), orderTicketBean);
                    }
                }.start();
            }
        }.start();

    }

    @Override
    public void onEventBusResult(MsgEventBus event) {
        super.onEventBusResult(event);
        if (event.getType().equals("扫码code")) {
            btQrcodeText.setText("反扫信息==" + event.getMessage());
        }

        if ("每层的设置返回".equals(event.getType())) {
            String data[] = event.getMessage().split(" ");
            builder.append("每层的设置返回==").append(event.getMessage()).append("==设置的层数 =").append(data[4]).append("\n");
            textTv.setText(builder.toString());
        }

        if ("保存所有的设置返回".equals(event.getType())) {
            String data[] = event.getMessage().split(" ");
            builder.append("保存所有的设置返回==").append(event.getMessage()).append("==是否成功 =").append(data[3].equals("01") ? "成功" : "失败").append("\n");
            textTv.setText(builder.toString());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        PrinterOperateUtils.getInstance().unConnectUsbPrinter();
    }

    @Override
    protected void onResume() {
        super.onResume();
        Constant.isShopShipment = true;
    }

    @Override
    public void onPause() {
        super.onPause();
        Constant.isShopShipment = false;
    }


    /**
     * 设置购买数量
     *
     * @param count
     */
    public void setCount(String count) {
        ShopApiHttp.set_mch_max_sale_count(count, new ApiListener() {
            @Override
            public void onRequestStart(String requestUrl, int requestId) {

            }

            @Override
            public void onRequestComplete(String requestUrl, int requestId) {

            }

            @Override
            public void onSuccess(String requestUrl, JSONObject requestJson, int requestId) {
                SharedUtils.getInstance().putInt(ShareKey.PURCHASE_COUNT, Integer.parseInt(count)); // 购买数量
            }

            @Override
            public void onError(String requestUrl, String errorMsg, String resultData, int requestId) {

            }
        });
    }
}
